//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package com.openbravo.pos.sales.shared;

import cn.ekuma.epos.businesslogic.RoleUtil;
import com.openbravo.bean.sales.SharedTicketInfo;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.base.AppView;
import cn.ekuma.epos.datalogic.I_DataLogicReceipts;
import cn.ekuma.util.ArrayQueue;

import com.openbravo.bean.sales.Ticket;
import java.util.*;
import javax.swing.*;

import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.pos.payment.JPaymentSelect;
import com.openbravo.pos.payment.JPaymentSelectReceipt;
import com.openbravo.pos.payment.JPaymentSelectRefund;
import com.openbravo.pos.printer.TicketPrinterException;
import com.openbravo.pos.sales.*;
import com.openbravo.pos.sales.event.TicketEvent;
import com.openbravo.pos.scripting.ScriptException;

@SuppressWarnings("serial")
public class JTicketsBagShared extends JTicketsBag {
	private ArrayQueue<Ticket> queue=new  ArrayQueue<Ticket>(5);
    protected String m_sCurrentTicket = null;
    protected I_DataLogicReceipts dlReceipts = null;
    
    
    /** Creates new form JTicketsBagShared */
    public JTicketsBagShared(AppView app, TicketsEditor panelticket) {
        
        super(app, panelticket);
        
        dlReceipts = panelticket.getDlReceipts();
        
        initComponents();
    }
    
    public void activate() {
        
        // precondicion es que no tenemos ticket activado ni ticket en el panel
        
        m_sCurrentTicket = null;
        selectValidTicket();     
        
        // Authorization
        m_jDelTicket.setEnabled(m_panelticket.getSecurityManager().hasPermissionByName("com.openbravo.pos.sales.JPanelTicketEdits"));
       
        // postcondicion es que tenemos ticket activado aqui y ticket en el panel
    }
    
    public boolean deactivate() {
        
        // precondicion es que tenemos ticket activado aqui y ticket en el panel 
   
    	saveAndUnLockedCurrentTicket();
        
        m_sCurrentTicket = null;
        m_panelticket.setActiveTicket(null, null,false);       
        
        return true;
        
        // postcondicion es que no tenemos ticket activado ni ticket en el panel
    }
    
    public void showNextTicket() {
		Ticket t=queue.next();
		if(t!=null){
			saveAndUnLockedCurrentTicket();

	        m_sCurrentTicket = null;
	        m_panelticket.setActiveTicket(t, null,false);
		}
	}

	public void showPrevTicket() {
		Ticket t=queue.prev();
		if(t!=null){
			saveAndUnLockedCurrentTicket();

	        m_sCurrentTicket = null;
	        m_panelticket.setActiveTicket(t, null,false);
		}
	}
        
    public void deleteTicket() {
    	Ticket t=m_panelticket.getActiveTicket();
        try {
            dlReceipts.deleteSharedTicket(m_sCurrentTicket);
            m_sCurrentTicket = null;
            newTicket(); 
        	for(I_TicketListener l:listenerList.getListeners(I_TicketListener.class))
    			try {
    				l.fireTicketDeleted(new TicketEvent(t));
    			} catch (TicketPrinterException e) {
    				e.printStackTrace();
    			} catch (ScriptException e) {
    				e.printStackTrace();
    		}
       } catch (BasicException ex) {
           MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), ex);
           msg.show(this);
       }
    }
    
    public JComponent getBagComponent() {
        return this;
    }
    
    public JComponent getNullComponent() {
        return new JPanel();
    }
   
    protected void saveCurrentTicket() {
    	if(!m_panelticket.isEditAble())
	    	return;
    	else
    		queue.resertCur();
        // save current ticket, if exists,
        if (m_sCurrentTicket != null) {    	
            	Ticket t=m_panelticket.getActiveTicket();
                for(I_TicketListener l:listenerList.getListeners(I_TicketListener.class))
					try {
						l.fireTicketSaved(new TicketEvent(t));
				} catch (TicketPrinterException e) {
						e.printStackTrace();
				}
        }
        // save current ticket, if exists,
        if (m_sCurrentTicket != null) {
            try {
                dlReceipts.insertSharedTicket(m_sCurrentTicket, m_panelticket.getActiveTicket());
            } catch (BasicException e) {
                new MessageInf(e).show(this);
            }  
        }    
    }
    
    protected void saveAndUnLockedCurrentTicket(){
        if (m_sCurrentTicket != null) {
            try {
                dlReceipts.updateSharedTicketAndUnLocked(m_sCurrentTicket,m_panelticket.getActiveTicket());
            } catch (BasicException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), e);
                msg.show(this);
            } 
        }
    }
    
    protected void insertAndLockedShardTicket(Ticket newTicket){
        if (m_sCurrentTicket != null) {
            try {
                dlReceipts.insertSharedTicket(m_sCurrentTicket, newTicket);
            } catch (BasicException e) {
                MessageInf msg = new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.storeShardOrderFailse"), e);
                 msg.show(this);
            }
        }
    }
    
    public void setActiveTicket(Ticket ticket) throws BasicException{
    	 saveAndUnLockedCurrentTicket();  
    	 m_sCurrentTicket = ticket.getId();
     	 dlReceipts.setSharedTicketLocked(m_sCurrentTicket,true,m_App.getAppUserView().getUser().getId());
     	 m_panelticket.setActiveTicket(ticket, null,true);
    }
    
    protected void setActiveTicket(String id) throws BasicException{
          
        // BEGIN TRANSACTION
        Ticket ticket = dlReceipts.getSharedTicket(id);
        if (ticket == null)  {
            // Does not exists ???
            throw new BasicException(AppLocal.getIntString("message.noticket"));
        } else {
        	dlReceipts.setSharedTicketLocked(id,true,m_App.getAppUserView().getUser().getId());
            m_sCurrentTicket = id;
            m_panelticket.setActiveTicket(ticket, null,true);
        } 
        Ticket t=m_panelticket.getActiveTicket();
        for(I_TicketListener l:listenerList.getListeners(I_TicketListener.class))
			try {
				l.fireTicketCreated(new TicketEvent(t));
			} catch (TicketPrinterException e) {
				e.printStackTrace();
			} catch (ScriptException e) {
				e.printStackTrace();
		}
        // END TRANSACTION                 
    }
    
    public void selectValidTicket() {
        try {
            List<SharedTicketInfo> l = dlReceipts.getSharedTicketList(m_App.getInventoryLocation());
            if (l.size() == 0) {
                newTicket();
            } else {
            	queue.resertCur();
            	setActiveTicket(l.get(0).getId());
            }
        } catch (BasicException e) {
            new MessageInf(e).show(this);
            newTicket();
        }    
    }    
    
    public void newTicket() {
    	saveAndUnLockedCurrentTicket();
        Ticket ticket = new Ticket();
        ticket.setLocation(m_App.getInventoryLocation());
        ticket.setHostName(m_App.getProperties().getHost());
        ticket.setUser(m_App.getAppUserView().getUser().getUserInfo());
        m_sCurrentTicket = UUID.randomUUID().toString(); // m_fmtid.format(ticket.getId());  
        m_panelticket.setActiveTicket(ticket, null,true); 
        insertAndLockedShardTicket(ticket);
        
        for(I_TicketListener l:listenerList.getListeners(I_TicketListener.class))
			try {
				l.fireTicketCreated(new TicketEvent(ticket));
			} catch (TicketPrinterException e) {
				e.printStackTrace();
			} catch (ScriptException e) {
				e.printStackTrace();
			}
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        m_jNewTicket = new javax.swing.JButton();
        m_jDelTicket = new javax.swing.JButton();
        m_jListTickets = new javax.swing.JButton();
        m_jRateTicket=new javax.swing.JButton();
        
        setLayout(new java.awt.BorderLayout());

        m_jNewTicket.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/editnew.png")));
        m_jNewTicket.setFocusPainted(false);
        m_jNewTicket.setFocusable(false);
        m_jNewTicket.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jNewTicket.setRequestFocusEnabled(false);
        m_jNewTicket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jNewTicketActionPerformed(evt);
            }
        });

        jPanel1.add(m_jNewTicket);

        m_jDelTicket.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/editdelete.png")));
        m_jDelTicket.setFocusPainted(false);
        m_jDelTicket.setFocusable(false);
        m_jDelTicket.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jDelTicket.setRequestFocusEnabled(false);
        m_jDelTicket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jDelTicketActionPerformed(evt);
            }
        });

        jPanel1.add(m_jDelTicket);

        m_jListTickets.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/unsortedList.png")));
        m_jListTickets.setFocusPainted(false);
        m_jListTickets.setFocusable(false);
        m_jListTickets.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jListTickets.setRequestFocusEnabled(false);
        m_jListTickets.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jListTicketsActionPerformed(evt);
            }
        });

        jPanel1.add(m_jListTickets);
 
        m_jRateTicket.setText("折");
        m_jRateTicket.setFocusPainted(false);
        m_jRateTicket.setFocusable(false);
        m_jRateTicket.setMargin(new java.awt.Insets(8, 14, 8, 14));
        m_jRateTicket.setRequestFocusEnabled(false);
        m_jRateTicket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	m_jRateTicketActionPerformed(evt);
            }
        });

        jPanel1.add(m_jRateTicket);

        add(jPanel1, java.awt.BorderLayout.WEST);

    }// </editor-fold>//GEN-END:initComponents

    public void m_jListTicket(){
        m_jListTicketsActionPerformed(null);
    }

    protected void m_jListTicketsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jListTicketsActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                
                try {
                    List<SharedTicketInfo> l = dlReceipts.getSharedTicketList(m_App.getInventoryLocation());

                    String id =getSharedListOrderId(l); 

                    if (id != null) {
                    	saveAndUnLockedCurrentTicket();
                        setActiveTicket(id); 
                    }
                } catch (BasicException e) {
                    new MessageInf(e).show(JTicketsBagShared.this);
                    newTicket();
                }                    
            }
        });
        
    }//GEN-LAST:event_m_jListTicketsActionPerformed

    protected void m_jDelTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jDelTicketActionPerformed
    	if(!m_panelticket.isEditAble())
    		return;
        int res = JOptionPane.showConfirmDialog(this, AppLocal.getIntString("message.wannadelete"), AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (res == JOptionPane.YES_OPTION) {
            deleteTicket();
        }
        
    }//GEN-LAST:event_m_jDelTicketActionPerformed

    protected void m_jNewTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jNewTicketActionPerformed
        newTicket();
        
    }//GEN-LAST:event_m_jNewTicketActionPerformed
    
    
    private void m_jRateTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jNewTicketActionPerformed
    	m_panelticket.changeTicketRate();
        
    }//GEN-LAST:event_m_jNewTicketActionPerformed(evt);
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton m_jDelTicket;
    private javax.swing.JButton m_jListTickets;
    private javax.swing.JButton m_jNewTicket;
    private javax.swing.JButton m_jRateTicket;
    // End of variables declaration//GEN-END:variables


	@Override
	public void flushTicket() {
		Ticket t=m_panelticket.getActiveTicket();
    	for(I_TicketListener l:listenerList.getListeners(I_TicketListener.class))
			try {
				l.fireTicketFlushed(new TicketEvent(t));
			} catch (TicketPrinterException e) {
				e.printStackTrace();
			} catch (ScriptException e) {
				e.printStackTrace();
		}
        queue.enqueue(t);
		m_sCurrentTicket = null;
	        //selectValidTicket();      
	    newTicket();
	}
	
	@Override
	public JPaymentSelect getPaymentdialogreceipt() {
		return  JPaymentSelectReceipt.getDialog(this);
	}

	@Override
	public JPaymentSelect getPaymentdialogrefund() {
		return  JPaymentSelectRefund.getDialog(this);
	}
	
	protected String getSharedListOrderId(List<SharedTicketInfo> l){
		JTicketsBagSharedList listDialog = JTicketsBagSharedList.newJDialog(JTicketsBagShared.this);
        return listDialog.showTicketsList(l); 

	}
    
}
